using System;
using System.Collections;
using System.Reflection;
using System.Web;
using System.Web.UI;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.Facilities.FactorySupport;
using Castle.MicroKernel;
using Castle.MicroKernel.Lifestyle;
using NDomain.ExampleModels.BloggingSystem.Infrastructure;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using NHibernate.Impl;

namespace NDomain.ExampleModels.BloggingSystem.Web
{
    public class Global : HttpApplication
    {
        public static IKernel Container;
     
        protected void Application_Start(object sender, EventArgs e)
        {
            Configuration configuration = new Configuration();
            Hashtable properties = new Hashtable();
            properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            properties.Add("hibernate.dialect", "NHibernate.Dialect.SQLiteDialect");
            properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SQLite20Driver");
            properties.Add("hibernate.connection.connection_string", "Data Source=nhibernate.db;Version=3");
            properties.Add("hibernate.query.substitutions", "true=1;false=0");
            properties.Add("hibernate.hbm2ddl.auto", "create");
            properties.Add("hibernate.current_session_context_class", "managed_web");

			Container = new DefaultKernel();

            configuration.AddProperties(properties);
            configuration.AddAssembly("NDomain.ExampleModels.BloggingSystem.Infrastructure");
			configuration.SetInterceptor(new NHibernateInterceptor(Container));
            
            Container.AddComponentInstance("SessionFactory", typeof(ISessionFactory), configuration.BuildSessionFactory());
            Container.AddComponent("BlogRepository", typeof(IBlogRepository), typeof(BlogRepositoryImpl));			
            Container.AddComponent("BlogFactory", typeof(IBlogFactory), typeof(BlogFactoryImpl));            
            Container.AddComponent("CurrentSession", typeof(ISession), typeof(CurrentSessionProxy));                                    
            
        }        

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            ((ISession)Container["CurrentSession"]).Dispose();
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            ManagedWebSessionContext.Bind(HttpContext.Current, ((ISessionFactory)Container["SessionFactory"]).OpenSession());
        }

        protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            IoCHelper.InjectDependencies(CurrentPage, Container);
        }

        private static Page CurrentPage
        {
            get { return HttpContext.Current.Handler as Page; }
        }
    }
}